package dy.com.udp.单播;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPSearcher {
    public static void main(String[] args) throws IOException {
        System.out.println("UDP searcher start");
        //作为发送方,无需设置监听端口
        DatagramSocket ds = new DatagramSocket();
        //构建发送的消息
        String send = "Hello world!";
        byte[] sendBytes = send.getBytes();
        //构建发送packet
        DatagramPacket responsePacket = new DatagramPacket(sendBytes,sendBytes.length);
        //设置ip
        responsePacket.setAddress(InetAddress.getLocalHost());
        //设置端口号
        responsePacket.setPort(20000);
        ds.send(responsePacket);
        System.out.println("我是searcher，已发送");

        final byte[] buffer = new byte[512];
        //接收实体
        DatagramPacket dp = new DatagramPacket(buffer,buffer.length);
        ds.receive(dp);

        //获得ip
        String ip  = dp.getAddress().getHostAddress();

        int port = dp.getPort();
        int dataLen = dp.getLength();
        String data = new String(dp.getData(),0,dataLen);
        System.out.println("我是searcher，我接收到来自"+ip+"地址，端口号为："+port+"，内容为："+data);
        //构建回送信息

        ds.close();
    }
}
